package com.shqcjd.preinstallmobile.ui.fragment.equipmentmanage;

import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.shqcjd.preinstallmobile.R;
import com.shqcjd.preinstallmobile.api.ApiService;
import com.shqcjd.preinstallmobile.helper.rxjavahelper.RxObserver;
import com.shqcjd.preinstallmobile.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.preinstallmobile.model.ResponseData;
import com.shqcjd.preinstallmobile.model.pojo.TaskNtrackBean;
import com.shqcjd.preinstallmobile.ui.activity.NtrackDetailsActivity;
import com.shqcjd.preinstallmobile.ui.adapter.NtrackAdapter;
import com.shqcjd.preinstallmobile.ui.base.BaseFragment;
import com.shqcjd.preinstallmobile.ui.base.BasePresenter;
import com.shqcjd.preinstallmobile.util.ToastUtils;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import io.reactivex.disposables.Disposable;

/**
 * 巡检轨迹
 * Created by sy on 2019/4/30.
 */

public class InspectioNtrackFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener {
    private static final int PAGE_SIZE = 7;
    private int mNextRequestPage = 1;
    @BindView(R.id.rv_ntrack_list)
    RecyclerView rvNtrackList;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;
    @BindView(R.id.et_search_expert)
    EditText etSearchExpert;
    private View notDataView;
    private NtrackAdapter ntrackAdapter;
    private String name;

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    public static InspectioNtrackFragment newInstance() {
        return new InspectioNtrackFragment();
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.fragment_inspection_ntrack;
    }

    @Override
    public void initView(View rootView) {
        notDataView = getLayoutInflater().inflate(R.layout.layout_no_data, (ViewGroup) rvNtrackList.getParent(), false);
        initAdapter();
    }

    private void initAdapter() {
        ntrackAdapter = new NtrackAdapter();
        rvNtrackList.setLayoutManager(new LinearLayoutManager(getContext()));
        rvNtrackList.setAdapter(ntrackAdapter);
        swipeLayout.setOnRefreshListener(this);
        ntrackAdapter.setOnLoadMoreListener(this,rvNtrackList);
        ntrackAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                //轨迹详情
                TaskNtrackBean.ItemsBean mBean = (TaskNtrackBean.ItemsBean) adapter.getData().get(position);
                Intent it = new Intent(getActivity(), NtrackDetailsActivity.class);
                it.putExtra("taskId", mBean.task_id);
                it.putExtra("routeId", mBean.route_id);
                startActivity(it);
            }
        });

        etSearchExpert.addTextChangedListener(new TextWatcher() {



            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                name = s.toString();
                refresh();
            }
        });

    }

    @Override
    public void initData() {
        name = "";
        refresh();
    }

    @Override
    public void onRefresh() {
        refresh();
    }

    @Override
    public void onLoadMoreRequested() {
        loadMore();
    }

    private void refresh() {
        mNextRequestPage = 1;
        //这里的作用是防止下拉刷新的时候还可以上拉加载
        ntrackAdapter.setEnableLoadMore(false);
        Map<String, String> map = new HashMap<>();
        map.put("pageIndex",mNextRequestPage+"");
        map.put("pageSize",PAGE_SIZE+"");
        map.put("user_name",name);

        ApiService.getNtrackList(new JSONObject(map))
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<TaskNtrackBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showRefreshView(true);
                    }

                    @Override
                    public void _onNext(ResponseData<TaskNtrackBean> retData) {
                        if (retData != null && retData.retCode == 10000) {
                            setData(true, retData.data.items);
                        } else {
                            ToastUtils.showShort(getContext(), retData.retMsg);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        ntrackAdapter.setEnableLoadMore(true);
                        showRefreshView(false);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        ntrackAdapter.setEnableLoadMore(true);
                        showRefreshView(false);
                    }
                });
    }

    private void loadMore() {
        Map<String, Integer> map = new HashMap<>();
        map.put("pageIndex",mNextRequestPage);
        map.put("pageSize",PAGE_SIZE);

        ApiService.getNtrackList(new JSONObject(map))
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<TaskNtrackBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData<TaskNtrackBean> retData) {
                        if (retData != null && retData.retCode == 10000) {
                            boolean isRefresh =mNextRequestPage ==1;
                            setData(isRefresh, retData.data.items);
                        } else {
                            ToastUtils.showShort(getContext(), retData.retMsg);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        ntrackAdapter.loadMoreFail();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                });
    }

    public void showRefreshView(Boolean refresh) {
        swipeLayout.post(new Runnable() {
            @Override
            public void run() {
                swipeLayout.setRefreshing(refresh);
            }
        });
    }

    private void setData(boolean isRefresh, List data) {
        mNextRequestPage++;
        final int size = data == null ? 0 : data.size();
        if (isRefresh) {
            if (size > 0) {
                ntrackAdapter.setNewData(data);
            } else {
                ntrackAdapter.setNewData(null);
                ntrackAdapter.setEmptyView(notDataView);
            }
        } else {
            if (size > 0) {
                ntrackAdapter.addData(data);
            }
        }
        if (size < PAGE_SIZE) {
            //第一页如果不够一页就不显示没有更多数据布局
            ntrackAdapter.loadMoreEnd(isRefresh);
        } else {
            ntrackAdapter.loadMoreComplete();
        }
    }
}
